package com.dq.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.Proxy;

/**
 * @ClassName: BeanPostProcessorHandler
 * @Description: Bean初始化环绕 设置单独Bean 多个Bean的环绕
 * @Author: spring-source_小强 (QQ:2680825683)
 * @Since: 2023/5/9 9:47
 */
@Component
public class BeanPostProcessorHandler implements BeanPostProcessor {
    /**
     * 实例化before
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if ("userService".equals(beanName)) {
            ((UserServiceImpl) bean).setProcessTest("杜小强");
        }
        return bean;
    }

    /**
     * 实例化after
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("环绕后");
        if (beanName.equals("userService")) {  //生成代理对象
            Object proxyInstance = Proxy.newProxyInstance(BeanPostProcessorHandler.class.getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
                System.out.println("代理逻辑");
                return method.invoke(bean, args); //执行业务逻辑
            });
            return proxyInstance;
        }
        return bean;
    }
}
